import React, {Component} from 'react';
import ArticleList from "../Home/ArticleList/ArticleList";
import ClassificationCard from "../Home/ClassificationCard/ClassificationCard";
import axios from "axios";
import {withRouter} from "react-router-dom";

class Search extends Component {

    state = {
        blogDescription: [],
        types: [],
        total: 0,
    }

    searchByTitle = (event) => {
        if (event.keyCode === 13) {
            if (!event.target.value.trim()) {
                /*global layer*/
                layer.msg("抱歉、搜索条件不能为空。");
                return;
            }
            axios("/blogs?page=1&limit=7&title=" + event.target.value).then(response => {
                this.setState({blogDescription: response.data.data.list});
                this.setState({total: response.data.data.total});
            })
        }
    }

    updateAll = () => {
        axios("/blogs/page/1/7").then((response) => {
            let {total, list, pages} = response.data.data;
            this.setState({total, pages, blogDescription: list});
        });
    }

    componentDidMount() {
        this.updateAll();

        axios("/types?page=1&limit=5").then((response) => {
            this.setState({types: response.data.data.list});
        });
    }

    updateBlogDescription = (blogDescription) => {
        this.setState({blogDescription})
    }

    render() {
        let {types, blogDescription, total} = this.state;
        return (
            <>
                <div className="layui-row vi-top">
                    <div className="layui-col-sm6 layui-col-sm-offset3">
                        <div className="layui-form-item layui-form layui-form-pane">
                            <label className="layui-form-label">全局搜索</label>
                            <div className="layui-input-block">
                                <input type="text" name="title" required placeholder="输入标题关键字全局搜索博文"
                                       autoComplete="off" className="layui-input" onKeyUp={this.searchByTitle}/>
                            </div>
                        </div>
                    </div>
                </div>
                <div className="layui-row vi-top  layui-col-space28">
                    <div className="layui-col-sm8">
                        <ArticleList total={total} blogDescription={blogDescription} updateBlogDescription={this.updateBlogDescription}/>
                    </div>
                    <div className="layui-col-sm4">
                        <ClassificationCard types={types} updateBlogDescription={this.updateBlogDescription}/>
                    </div>
                </div>
            </>
        );
    }
}

export default withRouter(Search);